<template>
  <div class="container">
    <div style="position: absolute;right: 1%;z-index: 9;">
      <el-button type="primary" @click="handleImport">导入</el-button>
      <el-button type="primary" @click="handleExport">导出</el-button>
      <el-button type="primary" @click="add">新增</el-button>
    </div>
    <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="列表" name="first">
        <el-table :data="tableData" style="width: 100%" :span-method="arraySpanMethod" v-loading="loading"
          height="100%">
          <el-table-column prop="deptName" label="单位"></el-table-column>
          <el-table-column prop="worker" label="值班人员"></el-table-column>
          <el-table-column prop="phoneNumber" label="手机"></el-table-column>
          <el-table-column prop="june" label="六月">
            <template #default="scope">
              {{ dealDate(scope.row.june) }}
            </template>
          </el-table-column>
          <el-table-column prop="july" label="七月">
            <template #default="scope">
              {{ dealDate(scope.row.july) }}
            </template>
          </el-table-column>
          <el-table-column prop="august" label="八月">
            <template #default="scope">
              {{ dealDate(scope.row.august) }}
            </template>
          </el-table-column>
          <el-table-column prop="september" label="九月">
            <template #default="scope">
              {{ dealDate(scope.row.september) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-icon title="编辑" @click="edit(scope.row)">
                <Edit />
              </el-icon>
              &nbsp;
              <el-icon title="删除" @click="del(scope.row)">
                <Delete />
              </el-icon>
            </template> </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="日历" name="second">
        <div style="float: left;">
          <span>值班人员&nbsp;&nbsp;</span>
          <el-select filterable v-model="value" style="width: 240px" @change="changePerson">
            <el-option v-for="item in optionsPerson" :key="item.userId" :label="item.userName" :value="item.userId" >
            <!-- <span style="float: left; margin-right: 10px;">{{ item.userName + "&nbsp;&nbsp;--&nbsp;&nbsp;" +item.deptName}}</span> -->
            <span style="float: left; margin-right: 10px;">{{item.userName}} <span v-show="item.deptName && item.deptName!= null">{{"&nbsp;&nbsp;--&nbsp;&nbsp;" + item.deptName}}</span></span>
          </el-option>
          </el-select>
        </div>

        <el-calendar ref="calendar" v-model="calendarValue">
          <template #header="{ date }">
            <span>{{ date }}&nbsp;&nbsp;</span>
            <el-button-group>
              <el-button size="small" @click="selectDate('prev-month')">
                上月
              </el-button>
              <!-- <el-button size="small" @click="selectDate('today')">今天</el-button> -->
              <el-button size="small" @click="selectDate('next-month')">
                下月
              </el-button>
            </el-button-group>
          </template>
          <template #date-cell="{ data }">
            <div :class="{ 'bgc': show(data) }">
              {{ data.day.split('-').slice(2).join('-') }}
            </div>
          </template>
        </el-calendar>

      </el-tab-pane>
    </el-tabs>

    <!-- 管理对话框 -->
    <el-dialog title="防洪值班管理" v-model="open" width="500px" append-to-body>

      <el-form ref="postRef" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="单位" prop="deptId">
          <el-tree-select v-model="form.deptId" :data="dataSource" :disabled="isdisabled"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
            check-strictly @change="treeChange">
          </el-tree-select>
        </el-form-item>
        <el-form-item label="值班人员" prop="workerIdList">
          <el-select v-model="form.workerIdList" placeholder="请选择" clearable multiple :disabled="isdisabled">
            <el-option v-for="item in all" :key="item.userId" :label="item.userName" :value="item.userId">
              
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="dateLists">
          <el-date-picker v-model="form.dateLists" type="dates" placeholder="选择日期" format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" :disabled-date="disabledDate"  :default-value="defaultDate[0]">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import {
    ElMessage,
    ElMessageBox
  } from 'element-plus'
  import {
    getDuty,
    delDuty,
    addDuty,
    getTreeList,
    getPersonBy,
    getDutyBy
  } from "@/api/work";
  const {
    proxy
  } = getCurrentInstance();

  // const disabledDate = (time) => {
  //   const month = time.getMonth() + 1;
  //   return month !== 6 && month !== 7 && month !== 8 && month !== 9;
  // };
  // const defaultTime = ref([])
  // function getCurrentYearAndMonth() {
    // const now = new Date();
    // const year = now.getFullYear();
    // const month = now.getMonth() + 1
    // if(month < 6){
    //   month = "06"
    // }else if(month > 9){
    //   month = "09"
    // }
    // defaultTime.value = [`${year}-${month}-01`]
    // console.log(`${year}-${month}-01`);
    
  // }
  const currentYear1 = ref([new Date().getFullYear()])
  const defaultDate = ref([new Date(currentYear1.value[0], 5, 1)])
  function disabledDate(time) {
      const currentYear = new Date().getFullYear();
      const startDate = new Date(currentYear, 5, 1); // 6月1日
      const endDate = new Date(currentYear, 8, 30); // 9月30日
      return time.getTime() < startDate.getTime() || time.getTime() > endDate.getTime();
    }
  // getCurrentYearAndMonth()
  const value = ref("") //值班人员

  const optionsPerson = ref([]) //值班人员下拉
  const workList = ref([])

  function changePerson(id) {
    getDutyBy({
      workerId: id
    }).then(res => {
      if (res.data.length) {
        let row = res.data[0]
        let august = row.august.split(",")
        let july = row.july.split(",")
        let june = row.june.split(",")
        let september = row.september.split(",")
        let lists = [].concat(june, july, august, september)
        workList.value = lists.filter(item => item != "")
      } else {
        workList.value = []
      }
    })
  }

  function dealDate(str) {
    if (str) {
      let arr = []
      let list = str.split(",")
      list.forEach(val => {
        if (val) {
          let date = new Date(val)
          let day = date.getDate()
          arr.push(day)
        }
      })
      return arr.join(",")
    } else {
      return ""
    }
  }

  function show(data) {
    return workList.value.some(item => item == data.day)

  }
  //获取数据
  function getPerson() {
    getPersonBy().then(res => {
      optionsPerson.value = JSON.parse(JSON.stringify(res.rows))
    })
  }
  getPerson()

  function getTree() {
    getTreeList().then(res => {
      dataSource.value = res.data
    })
  }
  getTree()
  //部门数据
  const dataSource = ref([])

  const all = ref([])

  function treeChange(id) {
    form.value.workerIdList = []
    getPersonBy({
      deptId: id
    }).then(res => {
      all.value = JSON.parse(JSON.stringify(res.rows))
    })
  }


  const open = ref(false)
  const isdisabled = ref(false)

  function edit(row) {
    isdisabled.value = true
    if (row.deptId) {
      getPersonBy({
        deptId: row.deptId
      }).then(res => {
        all.value = JSON.parse(JSON.stringify(res.rows))
      })
    }
    row.workerIdList = [row.workerId]
    row.dateLists = []

    // if (row.list.length) {
    //   row.list.forEach(item => {
    //     if (item.length) {
    //       item.forEach(val => {
    //         if (val.dutyId == row.dutyId) {
    //           row.workerIdList.push(val.workerId)
    //         }
    //       })
    //     }
    //   })
    // }
    let august = row.august.split(",")
    let july = row.july.split(",")
    let june = row.june.split(",")
    let september = row.september.split(",")
    let lists = [].concat(june, july, august, september)
    row.dateLists = lists.filter(item => item != "")
    form.value = JSON.parse(JSON.stringify(row))
    console.log(form.value, "form.value")
    open.value = true
  }

  function add() {
    isdisabled.value = false
    form.value = {}
    open.value = true
    all.value = []
  }

  function del(data) {
    ElMessageBox.confirm(
        '确认删除吗？',
        'Warning', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      .then(() => {
        delDuty(data.id).then(res => {
          ElMessage({
            type: 'success',
            message: '已删除',
          })
          getList()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
  }

  function cancel() {
    open.value = false
  }

  function submitForm() {
    if (form.value.workerIdList.length) {
      form.value.workerIdList = form.value.workerIdList.join(",")
    } else {
      form.value.workerIdList = ''
    }

    if (form.value.dateLists.length) {
      form.value.dateList = form.value.dateLists.join(",")
    } else {
      form.value.dateList = ''
    }
    proxy.$refs["postRef"].validate(valid => {
      if (valid) {
        if (form.value.dutyId != undefined) {
          addDuty(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList()
          });
        } else {
          addDuty(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList()
          });
        }
      }
    });
  }


  const tableData = ref([])
  const loading = ref(true);

  function getList() {
    loading.value = true
    tableData.value = []
    getDuty().then(res => {
      loading.value = false
      tableData.value = res.rows

      // span.value = tableRowMerges(tableData.value, 'dutyId')
    })
  }
  getList()
  const span = ref([])

  function tableRowMerges(
    data,
    rowName,
    otherRowName
  ) {
    const idArray = []
    let idPos = 0;
    for (let i = 0; i < data.length; i++) {
      if (i == 0) {
        idArray.push(1);
        idPos = 0;
      } else {
        if (data[i][rowName] == data[i - 1][rowName] && data[i][rowName] != "") {
          idArray[idPos] += 1;
          idArray.push(0);
        } else {
          idArray.push(1);
          idPos = i;
        }
      }
    }
    return idArray;
  }

  function arraySpanMethod({
    rowIndex,
    columnIndex,
    row
  }) {
    if (columnIndex === 0) {
      if (rowIndex > 0 && tableData.value[rowIndex].deptId === tableData.value[rowIndex -1].deptId) {
        return {rowspan: 0, colspan: 0}
      } else {
        let rowspan = 1;
        for(let i = rowIndex + 1; i < tableData.value.length; i++){
          if(tableData.value[i].deptId === row.deptId){
            rowspan++;
          }else{
            break;
          }
        }
        return {rowspan, colspan: 1}
      }
    }
    return {rowspan : 1, colspan: 1}
    // if (columnIndex == 7) {
    //   if (rowIndex == 0 || row.dutyId != tableData.value[rowIndex - 1].dutyId) {
    //     let rowspan = 0;
    //     tableData.value.forEach(element => {
    //       if (element.dutyId == row.dutyId) {
    //         rowspan++;
    //       }
    //     });
    //     return [rowspan, 1];
    //   } else {
    //     return [0, 0];
    //   }
    // }
    // if (columnIndex === 3 || columnIndex === 4 || columnIndex === 5 || columnIndex === 6) {
    //   const rowSpan = span.value[rowIndex];
    //   const colSpan = rowSpan > 0 ? 1 : 0;
    //   return {
    //     rowspan: rowSpan,
    //     colspan: colSpan
    //   }
    // }
  }
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      postCode: undefined,
      postName: undefined,
      phone: undefined
    },
    rules: {
      deptId: [{
        required: true,
        message: "单位不能为空",
        trigger: "change"
      }],
      workerIdList: [{
        required: true,
        message: "值班人员不能为空",
        trigger: "change"
      }],
      dateLists: [{
        required: true,
        message: "日期不能为空",
        trigger: "change"
      }],
    }
  });
  const {
    queryParams,
    form,
    rules
  } = toRefs(data);



  const activeName = ref('first')
  const handleClick = (tab, event) => {
    console.log(tab, event)
  }


  const calendarValue = ref()


  // const calendarValue = ref('')
  // //处理日期
  function handleDate() {
    let date = new Date(),str = ''
    let year = date.getFullYear()
    let mon = date.getMonth() + 1
    let day = date.getDate()
    if (mon > 5 && mon < 10) {
      str = `${year}-${mon}-${day}`
    } else {
      str = `${year}-6-1`
    }
    calendarValue.value = new Date(str)
  }
  handleDate()



  const calendar = ref()
  const selectDate = (val) => {
    if (!calendar.value) return
    console.log(calendarValue.value),
      console.log(val)
    let date = new Date(calendarValue.value)
    let mon = date.getMonth() + 1
    if ((val == 'prev-month' && mon == 6) || (val == 'next-month' && mon == 9)) {
      ElMessage({
        message: "只能查询6月到9月",
        type: 'warning'
      })
    } else {
      calendar.value.selectDate(val)
    }

  }
  import {
    getToken
  } from '@/utils/auth'
import { ref } from 'vue';
  /*** 导入参数 */
  const upload = reactive({
    // 是否显示弹出层
    open: false,
    // 弹出层标题
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: {
      Authorization: 'Bearer ' + getToken()
    },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/sjgtw-emergency/duty/importData',
  })
  /** 导入按钮操作 */
  function handleImport() {
    upload.title = '导入'
    upload.open = true
  }
  /** 下载模板操作 */
  function importTemplate() {
    proxy.download('sjgtw-emergency/duty/downloadTemplate', {}, `template_${new Date().getTime()}.xlsx`)
  }
  /** 文件上传成功处理 */
  const handleFileSuccess = (response, file, fileList) => {
    upload.open = false
    upload.isUploading = false
    proxy.$refs['uploadRef'].handleRemove(file)
    if (response.code == 200) {
      proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response
        .msg + '</div>', '导入结果', {
          dangerouslyUseHTMLString: true
        })
    } else {
      proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response
        .data + '</div>', '导入失败', {
          dangerouslyUseHTMLString: true
        })
    }
    getList()
  }
  /** 导出按钮操作 */
  function handleExport() {
    proxy.download("sjgtw-emergency/duty/export", {
      ...queryParams.value,
    }, `防洪值班${new Date().getTime()}.xlsx`);
  }
  /** 提交上传文件 */
  function submitFileForm() {
    proxy.$refs['uploadRef'].submit()
  }
  /**文件上传中处理 */
  const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true
  }
</script>

<style lang='scss' scoped>
  .container {
    position: relative;
    height: 100%;
    width: 100%;
    padding: 20px;
  }

  :deep(.el-calendar__header) {
    justify-content: flex-end;
  }

  :deep(.el-tabs) {
    height: 100%;
  }

  :deep(.el-tabs__content) {
    height: calc(100% - 40px);
  }

  :deep(.el-tab-pane) {
    height: 100%;
  }

  .top {
    height: 40px;
    line-height: 40px;
    display: flex;
    justify-content: flex-end;
  }

  :deep(.el-table .el-table__cell) {
    text-align: center;
  }

  :deep(.bgc) {
    background: #5c5cff;
    width: 100%;
    height: 100%;
    color: #fff;
  }
</style>